package drone.basis.util ;

import java.io.BufferedReader ;
import java.io.File ;
import java.io.InputStream ;
import java.io.InputStreamReader ;
import java.util.Objects ;

import ch.ethz.ssh2.Connection ;
import ch.ethz.ssh2.SCPClient ;
import ch.ethz.ssh2.SFTPv3Client ;
import ch.ethz.ssh2.Session ;
import ch.ethz.ssh2.StreamGobbler ;

public class SshUtil
{

	private Connection connection ;

	private Session session ;

	private SCPClient scp ;

	private SFTPv3Client sftp ;

	public SCPClient getScp ( )
	{
		return scp ;
	}

	public void setScp (
			SCPClient scp
	)
	{
		this.scp = scp ;
	}

	public SFTPv3Client getSftp ( )
	{
		return sftp ;
	}

	public void setSftp (
			SFTPv3Client sftp
	)
	{
		this.sftp = sftp ;
	}

	public Session getSession ( )
	{
		return session ;
	}

	public void setSession (
			Session session
	)
	{
		this.session = session ;
	}

	public Connection getConnection ( )
	{
		return connection ;
	}

	public void setConnection (
			Connection connection
	)
	{
		this.connection = connection ;
	}

	public void initial (
			String user ,
			String password ,
			String host
	) throws Exception
	{

		connection = new Connection ( host ) ;
		connection.connect ( ) ;
		boolean status = connection.authenticateWithPassword ( user , password ) ;
		if ( status )
		{
			session = connection.openSession ( ) ;
			scp = connection.createSCPClient ( ) ;
			sftp = new SFTPv3Client ( connection ) ;
		}

	}

	public void destory ( )
	{

		if ( ! Objects.isNull ( session ) )
		{
			session.close ( ) ;
		}
		if ( ! Objects.isNull ( connection ) )
		{
			connection.close ( ) ;
		}

	}

	public void setFile (
			String localFile ,
			String remoteFolder
	) throws Exception
	{

		scp.put ( localFile , remoteFolder ) ;
		return ;

	}

	public File getFile (
			String localFolder ,
			String remoteFolder ,
			String remoteFile
	) throws Exception
	{

		scp.get ( remoteFolder + remoteFile , localFolder ) ;
		return new File ( localFolder , remoteFile ) ;

	}

	public String command (
			String commandInfo
	) throws Exception
	{

		session.execCommand ( commandInfo ) ;

		InputStream stdout = new StreamGobbler ( session.getStdout ( ) ) ;
		BufferedReader br = new BufferedReader ( new InputStreamReader ( stdout ) ) ;

		StringBuffer sb = new StringBuffer ( ) ;
		String line = null ;
		while ( ( line = br.readLine ( ) ) != null )
		{
			sb.append ( line + System.lineSeparator ( ) ) ;
		}
		br.close ( ) ;

		return sb.toString ( ) ;

	}

}
